<template>
  <div class="page" v-loading="loading" element-loading-text="加载中...">
    <div class="edit-job-container .group_3">
      <div class="info-card">
        <div class="info-header">
          <div class="left-section">
            <h1 class="job-title">编辑任务</h1>
          </div>
        </div>

        <div class="basic-info-section">
          <div class="basic-info">
            <div class="info-item">
              <i class="el-icon-s-flag"></i>
              <span class="info-value">{{ jobForm.title }}</span>
            </div>

            <div class="info-item">
              <i class="el-icon-money"></i>
              <span class="reward">{{ jobForm.money }}r/题</span>
            </div>

            <div class="info-item">
              <i class="el-icon-user"></i>
              <span>已报名: {{ jobForm.joinedPeople }}</span>
            </div>

            <div class="info-item">
              <i class="el-icon-s-operation"></i>
              <span>{{ jobForm.group_count }}组 × {{ jobForm.group_size }}人</span>
            </div>

            <div class="info-item">
              <i class="el-icon-time"></i>
              <span>开始日期：{{ formattedStartTime }}</span>
            </div>

            <div class="info-item">
              <i class="el-icon-time"></i>
              <span>截止日期：{{ formattedEndTime }}</span>
            </div>
          </div>

          <div class="tag-container">
            <el-tag
              v-for="tag in jobForm.tags"
              :key="tag"
              size="medium"
              effect="plain"
              class="mr-2"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>

        <el-form ref="jobForm" :model="jobForm" :rules="rules" class="job-form">

          <div class="description-section">
            <label class="description-label">任务描述</label>
            <el-form-item prop="description" class="form-textarea">
              <div ref="quillEditor" class="quill-editor"></div>
            </el-form-item>
          </div>

          <el-form-item label="计分规则" prop="computePoints" class="form-textarea">
            <el-input
              type="textarea"
              v-model="jobForm.computePoints"
              :rows="6"
              placeholder="请输入计分规则"
            ></el-input>
          </el-form-item>

          <el-form-item class="form-buttons">
            <el-button type="primary" @click="submitForm('jobForm')">保存修改</el-button>
            <el-button @click="goBack">返回</el-button>
          </el-form-item>
        </el-form>
        </div>
      </div>
    </div>
</template>
</template>

<script>
import { fetchJobById, updateJob } from "@/api/api";
import Quill from "quill";
import "quill/dist/quill.snow.css";

export default {
  name: "EditJob",
  data() {
    return {
      quill: null,
      jobForm: {
        title: "",
        type: "",
        phase: "",
        tags: [],
        money: 0,
        totalParticipants: 1,
        description: "",
        computePoints: "",
      },
      formattedStartTime: "",
      formattedEndTime: "",
      defaultTags: ["技术", "设计", "写作", "研究", "分析", "创意"],
      rules: {
        title: [{ required: true, message: "请输入任务标题", trigger: "blur" }],
        type: [{ required: true, message: "请选择任务类型", trigger: "change" }],
        phase: [{ required: true, message: "请选择任务阶段", trigger: "change" }],
        money: [{ required: true, message: "请输入任务奖励", trigger: "blur" }],
        totalParticipants: [{ required: true, message: "请输入参与人数", trigger: "blur" }],
        description: [{ required: true, message: "请输入任务描述", trigger: "blur" }],
        computePoints: [{ required: true, message: "请输入计分规则", trigger: "blur" }],
        group_count: [{ required: true, message: "请输入组数", trigger: "blur" }],
        group_size: [{ required: true, message: "请输入每组人数", trigger: "blur" }],
        startTime: [{ required: true, message: "请选择开始日期", trigger: "change" }],
        endTime: [{ required: true, message: "请选择截止日期", trigger: "change" }],
      },
      jobId: null,
      loading: false,
    };
  },
  created() {
    this.jobId = this.$route.query.id;
    if (this.jobId) {
      this.fetchJobData();
    } else {
      this.$message.error("任务ID不存在");
      this.goBack();
    }
  },
  async mounted() {
    await this.$nextTick();
    await this.fetchJobData();
    this.initializeQuill();
  },
  methods: {
    async fetchJobData() {
      this.loading = true;
      try {
        const jobData = await fetchJobById(this.jobId);
        console.log("jobData", jobData);
        this.jobForm = {
          title: jobData.title || "",
          type: jobData.type || "",
          phase: jobData.phase || "",
          tags: jobData.tags ? jobData.tags.split(",").map(tag => tag.trim()) : [],
          money: jobData.money || 0,
          totalParticipants: jobData.totalParticipants || 1,
          description: jobData.description || "",
          computePoints: jobData.computePoints || "",
          group_count: jobData.group_count || 1,
          group_size: jobData.group_size || 1,
          startTime: jobData.startTime || "",
          endTime: jobData.endTime || "",
          joinedPeople: jobData.joinedPeople || 0,
        };
        this.formattedStartTime = this.jobForm.startTime ? new Date(this.jobForm.startTime).toISOString().split('T')[0] : '';
        this.formattedEndTime = this.jobForm.endTime ? new Date(this.jobForm.endTime).toISOString().split('T')[0] : '';
      } catch (error) {
        console.error("获取任务数据失败:", error);
        this.$message.error("获取任务数据失败");
        this.goBack();
      } finally {
        this.loading = false;
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.loading = true;
          try {
            const formData = {
              ...this.jobForm,
              tags: this.jobForm.tags.join(","),
            };
            await updateJob(this.jobId, formData);
            this.$message.success("保存成功");
            this.goBack();
          } catch (error) {
            console.error("保存失败:", error);
            this.$message.error("保存失败");
          } finally {
            this.loading = false;
          }
        } else {
          return false;
        }
      });
    },
    goBack() {
      this.$router.back();
    },
    initializeQuill() {
      const editor = this.$refs.quillEditor;
      if (!editor) return;

      this.quill = new Quill(editor, {
        theme: 'snow',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
            [{ 'script': 'sub'}, { 'script': 'super' }],
            [{ 'indent': '-1'}, { 'indent': '+1' }],
            [{ 'direction': 'rtl' }],
            [{ 'size': ['small', false, 'large', 'huge'] }],
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
            [{ 'color': [] }, { 'background': [] }],
            [{ 'font': [] }],
            [{ 'align': [] }],
            ['clean']
          ]
        },
        placeholder: '请输入任务描述'
      });

      // 设置初始内容
      if (this.jobForm.description) {
        this.quill.root.innerHTML = this.jobForm.description;
      }

      // 监听内容变化
      this.quill.on('text-change', () => {
        this.jobForm.description = this.quill.root.innerHTML;
      });
    },
  },
};
</script>

<style scoped>
.page {
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  padding: 20px;
}

.group_3 {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
}

.edit-job-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.info-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.info-header {
  margin-bottom: 30px;
}

.description-section {
  margin-bottom: 30px;
}

.description-label {
  display: block;
  font-size: 16px;
  color: #303133;
  margin-bottom: 12px;
  font-weight: 500;
}

.form-textarea {
  margin-bottom: 0;
}

.form-textarea :deep(.el-form-item__label) {
  display: none;
}
.job-title {
  font-size: 24px;
  color: #303133;
  margin: 0;
  padding: 0;
}

.job-form {
  margin-top: 20px;
}

.form-buttons {
  margin-top: 40px;
  text-align: center;
}

.form-buttons .el-button {
  min-width: 120px;
  margin: 0 10px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-input-number {
  width: 100%;
}

.quill-editor {
  height: 300px;
  margin-bottom: 20px;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .edit-job-container {
    padding: 10px;
  }

  .info-card {
    padding: 16px;
  }

  .el-form-item {
    margin-bottom: 16px;
  }
}

.basic-info-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
}

.basic-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.info-item i {
  font-size: 16px;
  color: #409EFF;
}

.info-value {
  color: #303133;
  font-weight: 500;
}

.reward {
  color: #F56C6C;
  font-weight: 500;
}

.tag-container {
  margin-top: 12px;
}

.tag-container .el-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}
</style>
